package xml

import groovy.xml.MarkupBuilder
import groovy.xml.XmlSlurper

String xmlStr = '''
    <response version-api="2.0">
        <value>
            <books id="1" classification="android">
                <book available="20" id="1">
                    <title>疯狂Android讲义</title>
                    <author id="1">李刚</author>
                </book>
                <book available="14" id="2">
                   <title>第一行代码</title>
                   <author id="2">郭林</author>
               </book>
               <book available="13" id="3">
                   <title>Android开发艺术探索</title>
                   <author id="3">任玉刚</author>
               </book>
               <book available="5" id="4">
                   <title>Android源码设计模式</title>
                   <author id="4">何红辉</author>
               </book>
           </books>
           <books id="2" classification="web">
               <book available="10" id="1">
                   <title>Vue从入门到精通</title>
                   <author id="4">李刚</author>
               </book>
           </books>
       </value>
    </response>
'''

def response = new XmlSlurper().parseText(xmlStr)
println response.value.books[0].book[0].@available // 获取标签属性
println response.value.books[1].book[0].title.text() //获取标签内的内容
println response.value.books[1].@classification

//深度遍历
//depthFirst 可以用'**'代替
def books = response.depthFirst().findAll { book ->
    book.author.text() == '李刚'
}

println books

//广度遍历
def titles = response.value.books.children().findAll {
    node -> node.author.text() == '李刚'
}.collect {
    node -> node.title.text()
}

println titles

def sw = new StringWriter()
def xmlBuilder = new MarkupBuilder(sw)

//xmlBuilder.langs(type: 'current', count: '3', mainstream: 'true') {
//    //子节点
//    language(flavor: 'static', version: 1.5) {
//        //没有子节点，没有属性
//        age(16)
//    }
//    language(flavor: 'dynamic', version: 1.6) {
//        //没有子节点，没有属性
//        age(17)
//    }
//}
def langs = new Langs()
xmlBuilder.langs(type: langs.type, count: langs.count, mainstream: langs.mainstream) {
    langs.languages.each { lang ->
        language(flavor: lang.flavor, version: lang.version) {
            age(lang.age)
        }
    }
}

println sw


class Langs {

    String type = 'current'
    int count = 3
    boolean mainstream = true

    List<Language> languages = [
            new Language(flavor: 'static', version: 1.5, age: 16),
            new Language(flavor: 'dynamic', version: 1.6, age: 17)
    ]

    class Language {
        String flavor
        int version

        int age
    }

}


/**
 * getRootProject
 * getRootProject
 * getSubProject
 * getParent
 *  project("project相对路径"){project->}   单独为指定的project配置
 *  allProject{}  配置当前rootProject和所有subProject
 *  subProject{project->}  配置当所有subProject
 *
 *  subProject默认继承rootProject的所有属性，可以直接在rootProject中扩展属性变量统一给subProject使用
 *
 *  扩展属性
 *  ext{}*
 *  file()  相对当前project定位获取File
 *
 */





